<template>
  <div>
    <treeselect v-if="componentsType === 'treeselect'"
                class="vueTreeselectShop"
                :style="{width: `${width}px`}"
                v-bind="$attrs"
                v-on="$listeners"
                :options='treeselectoptions'
                :normalizer='normalizer'
                :limitText='limitText'
                :limit='limit'
                :noResultsText='noResultsText'
                :value='value'
                search-nested
                :placeholder="placeholder"></treeselect>
    <iSelectShop v-bind="$attrs"
                 :width="width"
                 v-on="$listeners"
                 :value='value'
                 :permissionCode='permissionCode'
                 v-if="componentsType === 'iselect' "></iSelectShop>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import errorCaptured from '@/libs/errorCaptured'
import { getOrgAllTree } from '@/api/system/org'
import flattenDeep from '@/libs/flattenDeep'
import iSelectShop from '@/components/i-select-shop'

export default {
  name: 'vueTreeselectShop',
  components: {
    Treeselect,
    iSelectShop
  },

  props: {
    width: {
      type: Number,
      default: 180
    },
    componentsType: {
      type: String,
      default: 'treeselect' // treeselect 树形选择组件 iselect ：iview组件
    },
    value: [String, Array],
    options: {
      type: Array
    },
    noResultsText: {
      type: String,
      default: '未查询到结果'
    },
    limitText: {
      type: Function,
      default: () => {
        return '...'
      }
    },
    limit: {
      type: Number,
      default: 1
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    shopList: Array,
    normalizer: {
      type: Function,
      default: (node) => {
        return {
          id: node.id,
          label: node.orgName,
          children: node.childList && node.childList.length ? node.childList : undefined
        }
      }
    },
    permissionCode: { // 权限code
      type: String,
      required: false
    },
    merchantId: {
      type: String,
      default: ''
    }

  },
  data () {
    return {
      shopIds: []
      // currnValue: this.value
    }
  },
  computed: {
    treeselectoptions () {
      if (this.options) return this.options
      return this.shopIds
    }

  },
  watch: {
    // value(val) {
    //   this.currnValue = val
    // },
    // currnValue(val) {
    //   this.$e
    // },
  },
  // watch: {
  //   treeselectoptions (value) {
  //   }
  // },

  methods: {
    test () {
      console.log(this.value)
    },
    async getOrgAllTree () {
      let params = {
        perms: this.permissionCode, // 查看普通订单
        merchantId: this.merchantId || this.$store.state.user.merchantId, // 商户id
        orgType: 1
      }
      // if (this.permissionCode) {
      let [err, res] = await errorCaptured(getOrgAllTree, params)
      if (err) return null
      if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`)
      this.shopIds = [res.data.data]
      // 是否包含登录的id
      const findId = (arr) => {
        for (let item of arr) {
          if (item.id === this.$store.state.user.orgId) {
            isId = true
          } else if (Array.isArray(item.childList) && !isId) {
            findId(item.childList)
          }
        }
      }

      let isId = false
      findId(this.shopIds)
      // debugger
      this.$emit('on-api-finish', isId)
      // }
    },
    // 多选的时候使用 获取选中的店铺id
    async getShopId () {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          let value = this.value
          if (typeof value === 'string') return resolve(value)
          if (!value.length) return resolve(value)
          // if (!value.length) this.$emit('update:shopList', [])
          let ids = this.treeselectoptions.map(item => {
            // 选中并且是组织
            if (value.includes(item.id) && item.orgType !== 1 && item.childList && item.childList.length) {
              return this.flitterShopIDOrg(item.childList)
            } else if (value.includes(item.id) && item.orgType === 1) { // 选中的是店铺
              return item.id
              // 如果是组织
            } else if (item.orgType !== 1 && item.childList && item.childList.length) {
              return this.flitterShopIDItemShop(item.childList, value)
            }
          })
          resolve(flattenDeep(ids).filter(item => !!item))
        }, 50)
      })
      // return flattenDeep(ids).filter(item => !!item)
      // console.log('ids', ids)
      // console.log(ids.flat(Infinity).filter(item => !!item))
      // this.$nextTick(() => {
      //   if (this.statusList) {
      //     let selectIds = flattenDeep(ids).filter(item => !!item)
      //     this.$emit('update:shopList', selectIds)
      //     this.$emit('id-change', selectIds)
      //   }
      // })
      // this.$emit('input', value, instanceId)
      // return ids.flat(Infinity).filter(item => !!item)
    },
    // 过滤选中的组织
    flitterShopIDOrg (arr) {
      return arr.map(item => {
        if (item.orgType !== 1 && item.childList && item.childList.length) {
          return this.flitterShopIDOrg(item.childList)
        }
        return item.id
      })
    },
    // 选中的不是组织
    flitterShopIDItemShop (arr, value) {
      return arr.map(item => {
        if (value.includes(item.id) && item.orgType !== 1 && item.childList && item.childList.length) {
          return this.flitterShopIDOrg(item.childList)
        } else if (value.includes(item.id) && item.orgType === 1) { // 选中的是店铺
          return item.id
          // 如果是组织
        } else if (item.orgType !== 1 && item.childList && item.childList.length) {
          return this.flitterShopIDItemShop(item.childList, value)
        }
      })
    }

  },
  created () {
    if (this.componentsType === 'treeselect') this.getOrgAllTree()
  }
}
</script>

<style lang="less" scoped>
</style>
<style lang="less">
.vueTreeselectShop {
  .vue-treeselect__multi-value {
    line-height: normal;
    margin-bottom: 0px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .vue-treeselect__multi-value-label {
    line-height: normal;
    margin-bottom: 0px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    max-width: 80px;
  }
  .vue-treeselect__limit-tip {
    padding-top: 0px;
  }
  .vue-treeselect__multi-value-item-container {
    padding-top: 5px;
  }
  .vue-treeselect__multi-value-item {
    cursor: pointer;
    display: inline-table;
    background: #e3f2fd;
    padding: 0 0;
    border: 1px solid transparent;
    border-radius: 2px;
    color: #039be5;
    font-size: 12px;
    vertical-align: top;
  }
  .vue-treeselect__menu-container {
    width: 300px;
  }
  .vue-treeselect__control {
    height: 32px;
  }
}
</style>
